// taskmanager.cpp
#include "taskmanager.h"
#include <QDebug>
#include <QDateTime>
#include <QTimer>
#include <DatabaseManager/DatabaseManager.h>

TaskManager& TaskManager::instance()
{
    static TaskManager instance;
    return instance;
}

TaskManager::TaskManager(QObject* parent)
    : QObject(parent)
    , m_isExecuting(false)
{
    // 初始化当前任务为空
    m_currentTask = HardwareTaskQueue();
}

void TaskManager::log(const QString &message)
{
    qDebug() << "[TaskManager]" << message;
    emit logMessage(message);
}

void TaskManager::addPendingTask(const HardwareTaskQueue& task)
{
    QMutexLocker locker(&m_mutex);

    // 检查任务是否已经在队列中
    for (const auto& pendingTask : m_pendingTasks) {
        if (pendingTask.id == task.id) {
            qWarning() << "任务已在队列中:" << task.id;
            return;
        }
    }

    // 检查任务状态是否为待执行
    if (task.status != TaskStatus::PENDING) {
        qWarning() << "任务状态不是待执行，跳过添加:" << task.id << "状态:" << static_cast<int>(task.status);
        return;
    }

    m_pendingTasks.enqueue(task);
    qDebug() << "任务添加到队列:" << task.id << task.task_name << "类型:" << static_cast<int>(task.task_type);

    // 如果没有正在执行的任务，立即开始执行
    if (!m_isExecuting) {
        QTimer::singleShot(0, this, &TaskManager::startNextTask);
    }
}

void TaskManager::startNextTask()
{
    QMutexLocker locker(&m_mutex);

    if (m_isExecuting || m_pendingTasks.isEmpty()) {
        return;
    }

    // 从队列中取出下一个任务
    m_currentTask = m_pendingTasks.dequeue();
    m_isExecuting = true;

    qDebug() << "开始执行任务 - ID:" << m_currentTask.id
             << "名称:" << m_currentTask.task_name
             << "类型:" << static_cast<int>(m_currentTask.task_type);

    // 更新任务状态为执行中（直接更新数据库）
    if (updateStatus(TaskStatus::EXECUTING, "任务开始执行")) {
        // 更新内存中的任务状态
        m_currentTask.status = TaskStatus::EXECUTING;
        m_currentTask.start_time = QDateTime::currentDateTime();
        m_currentTask.updated_time = QDateTime::currentDateTime();

        // 发出执行信号
        emit taskStarted(m_currentTask);
    } else {
        // 数据库更新失败，跳过这个任务
        qWarning() << "任务状态更新失败，跳过任务:" << m_currentTask.id;
        m_currentTask = HardwareTaskQueue();
        m_isExecuting = false;

        // 继续下一个任务
        if (!m_pendingTasks.isEmpty()) {
            QTimer::singleShot(0, this, &TaskManager::startNextTask);
        }
    }
}

void TaskManager::addPendingTasks(const QList<HardwareTaskQueue>& tasks)
{
    QMutexLocker locker(&m_mutex);

    for (const auto& task : tasks) {
        // 检查重复
        bool exists = false;
        for (const auto& pendingTask : m_pendingTasks) {
            if (pendingTask.id == task.id) {
                exists = true;
                break;
            }
        }

        if (!exists && task.status == TaskStatus::PENDING) {
            m_pendingTasks.enqueue(task);
            qDebug() << "批量添加任务到队列:" << task.id << task.task_name << "类型:" << static_cast<int>(task.task_type);
        }
    }

    // 如果没有正在执行的任务，立即开始执行
    if (!m_isExecuting && !m_pendingTasks.isEmpty()) {
        QTimer::singleShot(0, this, &TaskManager::startNextTask);
    }
}

bool TaskManager::hasPendingTasks() const
{
    QMutexLocker locker(&m_mutex);
    return !m_pendingTasks.isEmpty();
}

int TaskManager::pendingTaskCount() const
{
    QMutexLocker locker(&m_mutex);
    return m_pendingTasks.size();
}

HardwareTaskQueue TaskManager::getCurrentTask() const
{
    QMutexLocker locker(&m_mutex);
    return m_currentTask;
}

bool TaskManager::isTaskExecuting() const
{
    QMutexLocker locker(&m_mutex);
    return m_isExecuting;
}

void TaskManager::clearPendingTasks()
{
    QMutexLocker locker(&m_mutex);
    m_isExecuting = false;
    // 清空待执行队列
    while (!m_pendingTasks.isEmpty()) {
        HardwareTaskQueue task = m_pendingTasks.dequeue();
        qDebug() << "清除待执行任务:" << task.id;
    }
}

bool TaskManager::completeTaskStatus(TaskType taskType,bool success, const QString& message)
{
    // 检查是否是当前任务
    if (!m_isExecuting || m_currentTask.id == 0) {
        qWarning() << "没有正在执行的任务，忽略状态更新:" << static_cast<int>(taskType);
        return false;
    }

    // 检查任务类型是否匹配
    if (m_currentTask.task_type != taskType) {
        qWarning() << "任务类型不匹配，当前任务类型:" << static_cast<int>(m_currentTask.task_type)
                 << "更新类型:" << static_cast<int>(taskType);
        return false;
    }



    TaskStatus status = success ? TaskStatus::SUCCESS : TaskStatus::FAILED;

    // 完成任务
    updateStatus(status, message);

    // 开始下一个任务
    if (!m_pendingTasks.isEmpty()) {
        QTimer::singleShot(0, this, &TaskManager::startNextTask);
    }

    return true;
}

bool TaskManager::updateStatus(TaskStatus status,const QString& resultMessage) {

    DatabaseManager& dbManager = DatabaseManager::instance();
    if (!dbManager.isConnected()) {
        log("❌ 无法更新任务状态：数据库未连接");
        return false;
    }
    QVariantMap updateData;
    updateData["status"] = static_cast<int>(status);
    updateData["updated_time"] = QDateTime::currentDateTime();

    if (!resultMessage.isEmpty()) {
        updateData["result_message"] = resultMessage;
    }

    if (status == TaskStatus::EXECUTING) {
        updateData["start_time"] = QDateTime::currentDateTime();
    } else if (status == TaskStatus::SUCCESS || status == TaskStatus::FAILED) {
        m_isExecuting = false;
        updateData["end_time"] = QDateTime::currentDateTime();
    }

    QVariantMap whereParams;
    whereParams["id"] = m_currentTask.id;

    bool success = dbManager.updateData("hardware_task_queue", updateData,
                                        "id = :id", whereParams);
    if (!success) {
        log(QString("❌ 任务状态更新失败: %1").arg(dbManager.lastError()));
        return false;
    }
    return success;
}
